package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.Result;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ydd_user")
public class YddUserController {
    @Autowired
    private YddUserService yddUserService;

    /**
     * 会员用户详情
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public Result getYddUser(String id){
        YddUser yddUser = yddUserService.getById(id);
        return Result.ok("",yddUser);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/list")
    public Result getList(String sex,String username,String mobile,Integer page,Integer limit){
        Page<YddUser>pageInfo = new Page<>(page,limit);
        LambdaQueryWrapper<YddUser>lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.hasText(sex),YddUser::getSex,sex);
        lqw.like(StringUtils.hasText(username),YddUser::getUsername,username);
        lqw.like(StringUtils.hasText(mobile),YddUser::getMobile,mobile);
        lqw.orderByDesc(YddUser::getId);
        yddUserService.page(pageInfo,lqw);
        return Result.ok("", PageResult.init(pageInfo));

    }

    /**
     *
     * 添加会员
     * @param yddUser
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody YddUser yddUser){
        yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
        yddUser.setBirthday("1999-9-9");
        yddUserService.save(yddUser);
        return Result.ok("添加成功", null);
    }

    /**
     * 删除会员
     * @param id
     * @return
     */
    @GetMapping("/del")
    public Result delete(String id){
        yddUserService.removeById(id);
        return Result.ok("删除成功",null);
    }

    /**
     * 修改会员
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public Result update( @RequestBody YddUser yddUser){
        log.info(yddUser.toString());
        //yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
        yddUserService.updateById(yddUser);
        return Result.ok("修改成功",null);
    }
}
